package com.jsz.peini.component;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.security.KeyStore;
import java.util.Iterator;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import com.jsz.peini.util.constant.Config;

@Component
public class HttpClientComponent {
	private Logger logger = LogManager.getLogger(HttpClientComponent.class);
	@Autowired
	private CloseableHttpClient httpClient;
	@Autowired
	private RequestConfig requestConfig;

	public String getHttpGet(String scheme, String host, String path, Map<String, String> param) {
		CloseableHttpResponse response = null;
		try {
			URIBuilder uriBuilder = new URIBuilder().setScheme(scheme).setHost(host).setPath(path);
			if (param != null) {
				Iterator<String> iterator = param.keySet().iterator();
				while (iterator.hasNext()) {
					String key = iterator.next();
					uriBuilder.addParameter(key, param.get(key));
				}
			}
			URI uri = uriBuilder.build();
			HttpGet httpGet = new HttpGet(uri);
			httpGet.setConfig(requestConfig);
			logger.debug(httpGet.getURI().toString());
			response = httpClient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == 200) {
				return EntityUtils.toString(response.getEntity(), "utf-8");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
		}
		return null;
	}

	public String getHttpPost(String scheme, String host, String path, Map<String, String> param, String requestBody) {
		CloseableHttpResponse response = null;
		try {
			URIBuilder uriBuilder = new URIBuilder().setScheme(scheme).setHost(host).setPath(path);
			if (param != null) {
				Iterator<String> iterator = param.keySet().iterator();
				while (iterator.hasNext()) {
					String key = iterator.next();
					uriBuilder.addParameter(key, param.get(key));
				}
			}
			URI uri = uriBuilder.build();
			// URI uri = new URIBuilder().setScheme(scheme).setHost(host).setPath(path).build();
			HttpPost httpPost = new HttpPost(uri);
			httpPost.setEntity(new StringEntity(requestBody, "UTF-8"));
			httpPost.setConfig(requestConfig);
			response = httpClient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == 200) {
				return EntityUtils.toString(response.getEntity(), "utf-8");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
		}
		return null;
	}

	public String getHttpSSLPost(String scheme, String host, String path, Map<String, String> param, String requestBody) {
		// return getHttpPost(scheme, host, path, param, requestBody);
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		FileInputStream instream = null;
		try {
			KeyStore keyStore = KeyStore.getInstance("PKCS12");
			instream = new FileInputStream(ResourceUtils.getFile("classpath:apiclient_cert.p12"));
			keyStore.load(instream, Config.weixin_payno_mch_id.toCharArray());

			SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, Config.weixin_payno_mch_id.toCharArray()).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
			httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
			URIBuilder uriBuilder = new URIBuilder().setScheme(scheme).setHost(host).setPath(path);
			if (param != null) {
				Iterator<String> iterator = param.keySet().iterator();
				while (iterator.hasNext()) {
					String key = iterator.next();
					uriBuilder.addParameter(key, param.get(key));
				}
			}
			URI uri = uriBuilder.build();
			HttpPost httpPost = new HttpPost(uri);
			httpPost.setEntity(new StringEntity(requestBody, "UTF-8"));
			httpPost.setConfig(requestConfig);
			response = httpclient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == 200) {
				return EntityUtils.toString(response.getEntity(), "utf-8");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			if (response != null) {
				try {
					instream.close();
					response.close();
					httpclient.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
		}
		return null;
	}
}
